﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StationUpdate.Enty;
using System.Threading;
using System.IO;
using StationUpdate.Util;

namespace StationUpdate
{
    public partial class MainForm : Form
    {
        Thread thDownFile;
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {

                SysLog.logPath = Application.StartupPath + "\\Log";
                SysLog.WriteTxtLog("系统启动。");

                initGridView();
                getSys();

                startThread();
            }
            catch (Exception ex)
            {
                SysLog.WriteTxtLog("系统启动异常：" + ex.Message);
            }
        }
        private void getSys()
        {
            try
            {
                SysData.webService = IniOperate.IniValue(System.Windows.Forms.Application.StartupPath + "//sys.ini", "系统配置", "webService");
                SysData.serverPort = IniOperate.IniValue(System.Windows.Forms.Application.StartupPath + "//sys.ini", "系统配置", "serverPort");

                SysData.appId = IniOperate.IniValue(System.Windows.Forms.Application.StartupPath + "//sys.ini", "系统配置", "appId");
                SysData.appKey = IniOperate.IniValue(System.Windows.Forms.Application.StartupPath + "//sys.ini", "系统配置", "appKey");
                
            }
            catch (Exception ex)
            {
                SysLog.WriteTxtLog("读取sys.ini文件异常：" + ex.Message);
            }
        }
        private void startThread()
        {
            try
            {
                thDownFile = new Thread(new ThreadStart(downFileMethod));
                thDownFile.IsBackground = true;
                thDownFile.Start();

                SysData.serverOpen = true;

                //页面更新线程
                new Thread(new ThreadStart(() =>
                {
                    updateUi();
                })).Start();

                new Thread(new ThreadStart(() =>
                {
                    startServer();
                })).Start();
            }
            catch (Exception ex)
            {
                SysLog.WriteTxtLog("startThread（）方法中异常："+ex.Message);
            }
        }
        private void downFileMethod()
        {
            while (true)
            {
                try
                {
                    foreach (SjFileInfo enty in SysData.listSjFileInfo)
                    {
                        if (enty.isComple)
                        {//下载完成的不用处理
                            continue;
                        }
                        if (Util.WebDown.DeownloadFile(enty.sjServerFileName, enty.sjLocalFileName))
                        {
                            enty.EzoneFile = new FileInfo(enty.sjLocalFileName);
                            enty.EzoneStream = enty.EzoneFile.OpenRead();
                            enty.isComple = true;
                        }

                        if (enty.isComple && (DateTime.Now - enty.lastUseTime).Minutes > 30 && enty.EzoneStream != null)
                        {//超过30分钟未使用，同时已下载完成的，所以要关闭
                            enty.EzoneStream.Close();
                            enty.EzoneStream.Dispose();
                        }

                    }
                }
                catch (Exception ex)
                {
                    SysLog.WriteTxtLog("下载文件时异常：" + ex.Message);
                }

                Thread.Sleep(1000);
            }
        }
        
        #region 其它方法
        private void startServer() 
        {
            try
            {
                if (!SysData.isStartServer)
                {
                    SysData.isStartServer = true;

                    SocketOp sop = new SocketOp();
                    sop.Port = Convert.ToInt32(SysData.serverPort);
                    sop.Type = OpType.Server;
                    sop.Start();
                }
            }
            catch (Exception ex) 
            {
                SysLog.WriteTxtLog("服务启动异常：" + ex.Message);
            }
        }
        private void updateUi()
        {
            while (true)
            {
                if (!SysData.serverOpen)
                {
                    break;
                }
                try
                {
                    lock (SysData.objSyn)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            int updateSuccessCount = 0;
                            foreach (string key in SysData.dicTermStation.Keys)
                            {
                                if (SysData.dicTermStation[key].CurUpdateSize == SysData.dicTermStation[key].FileSize)
                                {
                                    updateSuccessCount++;
                                }

                                string stationId = SysData.dicTermStation[key].TermId;
                                bool exitsRow = false;
                                for (int i = 0; i < dgvStation.Rows.Count; i++)
                                {
                                    if (Convert.ToString(dgvStation.Rows[i].Cells["termId"].Value) == stationId)
                                    {
                                        addRowGridView(i, key);
                                        exitsRow = true;
                                        break;
                                    }
                                }
                                if (!exitsRow)
                                {
                                    int addRowIndex = dgvStation.Rows.Add();
                                    addRowGridView(addRowIndex, key);
                                }
                            }

                            this.lblConnectCount.Text = "已连接终端数："+dgvStation.Rows.Count;
                            this.lblUpdateSucessCount.Text = "成功升级数：" + updateSuccessCount;
                        }));
                    }
                }
                catch (Exception ex)
                {
                    SysLog.WriteTxtLog("更新页面时异常：" + ex.Message);
                }
                Thread.Sleep(3 * 1000);
            }
        }

        private void addRowGridView(int rowIndex, string key)
        {
            dgvStation.Rows[rowIndex].Cells["termId"].Value = SysData.dicTermStation[key].TermId;
            dgvStation.Rows[rowIndex].Cells["curUpdateSize"].Value = SysData.dicTermStation[key].CurUpdateSize;
            dgvStation.Rows[rowIndex].Cells["fileSize"].Value = SysData.dicTermStation[key].FileSize;
            dgvStation.Rows[rowIndex].Cells["softVer"].Value = SysData.dicTermStation[key].SoftVer;
            dgvStation.Rows[rowIndex].Cells["hardWareVer"].Value = SysData.dicTermStation[key].HardWareVer;
            dgvStation.Rows[rowIndex].Cells["updateTime"].Value = SysData.dicTermStation[key].LastUpdateTime;

        }

        private void initGridView()
        {
            //初始化GridView
            dgvStation.ReadOnly = true;
            DataGridViewColumn dgvcl1 = new DataGridViewTextBoxColumn();
            dgvcl1.HeaderText = "设备编号";
            dgvcl1.Name = "termId";
            dgvcl1.Width = 150;
            dgvStation.Columns.Add(dgvcl1);

            DataGridViewColumn dgvcl2 = new DataGridViewTextBoxColumn();
            dgvcl2.HeaderText = "当前已成功升级包数";
            dgvcl2.Name = "curUpdateSize";
            dgvcl2.Width = 200;
            dgvStation.Columns.Add(dgvcl2);

            DataGridViewColumn dgvcl12 = new DataGridViewTextBoxColumn();
            dgvcl12.HeaderText = "包总数";
            dgvcl12.Name = "fileSize";
            dgvcl12.Width = 200;
            dgvStation.Columns.Add(dgvcl12);

            DataGridViewColumn dgvcl3 = new DataGridViewTextBoxColumn();
            dgvcl3.HeaderText = "客户端软件版本";
            dgvcl3.Name = "softVer";
            dgvcl3.Width = 200;
            dgvStation.Columns.Add(dgvcl3);

            DataGridViewColumn dgvcl4 = new DataGridViewTextBoxColumn();
            dgvcl4.HeaderText = "客户端硬件版本";
            dgvcl4.Name = "hardWareVer";
            dgvcl4.Width = 200;
            dgvStation.Columns.Add(dgvcl4);

            DataGridViewColumn dgvcl5 = new DataGridViewTextBoxColumn();
            dgvcl5.HeaderText = "最近一次更新时间";
            dgvcl5.Name = "updateTime";
            dgvcl5.Width = 200;
            dgvStation.Columns.Add(dgvcl5);

        }
    
        #endregion

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show(this, "您确定要退出吗?", "提示", MessageBoxButtons.YesNo)
                    == System.Windows.Forms.DialogResult.Yes)
            {
                System.Environment.Exit(0);
            }
            else 
            {
                e.Cancel = true;
            }
        }
    }
}
